<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RealESRGAN 图像超分辨率工具</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        body {
            background-color: #f0f2f5;
            color: #333;
            line-height: 1.6;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }
        h1 {
            color: #2c3e50;
            margin-bottom: 10px;
        }
        .subtitle {
            color: #7f8c8d;
            font-size: 1.2rem;
        }
        .upload-container {
            background-color: white;
            border-radius: 8px;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
        }
        .upload-area {
            border: 2px dashed #3498db;
            border-radius: 5px;
            padding: 30px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 20px;
        }
        .upload-area:hover {
            border-color: #2980b9;
            background-color: #f7f9fc;
        }
        .upload-area i {
            font-size: 50px;
            color: #3498db;
            margin-bottom: 15px;
        }
        .upload-area p {
            color: #7f8c8d;
        }
        .upload-area.highlight {
            border-color: #2ecc71;
            background-color: #eafaf1;
        }
        #upload-btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 1rem;
            transition: background-color 0.3s;
        }
        #upload-btn:hover {
            background-color: #2980b9;
        }
        #upload-btn:disabled {
            background-color: #bdc3c7;
            cursor: not-allowed;
        }
        #file-input {
            display: none;
        }
        .preview-container {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 20px;
            margin-top: 30px;
        }
        .preview-box {
            flex: 1;
            min-width: calc(50% - 20px);
            background-color: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .preview-box h3 {
            margin-bottom: 15px;
            color: #2c3e50;
            text-align: center;
        }
        .image-container {
            width: 100%;
            position: relative;
            overflow: hidden;
            border-radius: 5px;
            height: 400px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f7f9fc;
        }
        .image-container img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
        .loading-spinner {
            border: 5px solid #f3f3f3;
            border-top: 5px solid #3498db;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 2s linear infinite;
            margin: 20px auto;
            display: none;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .download-btn {
            display: block;
            width: 100%;
            background-color: #2ecc71;
            color: white;
            border: none;
            padding: 10px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 1rem;
            margin-top: 15px;
            transition: background-color 0.3s;
            text-align: center;
            text-decoration: none;
        }
        .download-btn:hover {
            background-color: #27ae60;
        }
        .status-message {
            text-align: center;
            margin: 10px 0;
            color: #7f8c8d;
        }
        .error-message {
            color: #e74c3c;
            text-align: center;
            margin: 10px 0;
            display: none;
        }
        footer {
            text-align: center;
            margin-top: 50px;
            padding-top: 20px;
            border-top: 1px solid #ddd;
            color: #7f8c8d;
        }
        /* 响应式调整 */
        @media (max-width: 768px) {
            .preview-container {
                flex-direction: column;
            }
            .preview-box {
                min-width: 100%;
            }
            .image-container {
                height: 300px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>RealESRGAN 图像超分辨率工具</h1>
            <p class="subtitle">使用AI技术提升您的图像质量</p>
        </header>

        <div class="upload-container">
            <div class="upload-area" id="upload-area">
                <div>
                    <svg width="50" height="50" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 5V19M12 5L18 11M12 5L6 11" stroke="#3498db" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </div>
                <h3>拖放图片到这里</h3>
                <p>或点击浏览文件</p>
                <input type="file" id="file-input" accept="image/*">
            </div>
            <button id="upload-btn" disabled>放大图像</button>
            <p class="status-message" id="status-message">请选择要放大的图像</p>
            <p class="error-message" id="error-message"></p>
            <div class="loading-spinner" id="loading-spinner"></div>
        </div>

        <div class="preview-container">
            <div class="preview-box">
                <h3>原始图像</h3>
                <div class="image-container" id="original-image-container">
                    <p>未选择图像</p>
                </div>
                <div id="original-image-info"></div>
            </div>
            <div class="preview-box">
                <h3>放大图像 (4倍)</h3>
                <div class="image-container" id="upscaled-image-container">
                    <p>处理后的图像将显示在这里</p>
                </div>
                <div id="upscaled-image-info"></div>
                <a class="download-btn" id="download-btn" style="display: none;" target="_blank" rel="noopener noreferrer">下载放大后的图像</a>
            </div>
        </div>

        <footer>
            <p>由 RealESRGAN 提供支持 - 一种用于图像超分辨率的深度学习模型</p>
        </footer>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const uploadArea = document.getElementById('upload-area');
            const fileInput = document.getElementById('file-input');
            const uploadBtn = document.getElementById('upload-btn');
            const statusMessage = document.getElementById('status-message');
            const errorMessage = document.getElementById('error-message');
            const loadingSpinner = document.getElementById('loading-spinner');
            const originalImageContainer = document.getElementById('original-image-container');
            const upscaledImageContainer = document.getElementById('upscaled-image-container');
            const originalImageInfo = document.getElementById('original-image-info');
            const upscaledImageInfo = document.getElementById('upscaled-image-info');
            const downloadBtn = document.getElementById('download-btn');
            
            let selectedFile = null;
            
            // 处理上传区域点击
            uploadArea.addEventListener('click', function() {
                fileInput.click();
            });
            
            // 处理拖放事件
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                uploadArea.addEventListener(eventName, preventDefaults, false);
            });
            
            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }
            
            ['dragenter', 'dragover'].forEach(eventName => {
                uploadArea.addEventListener(eventName, highlight, false);
            });
            
            ['dragleave', 'drop'].forEach(eventName => {
                uploadArea.addEventListener(eventName, unhighlight, false);
            });
            
            function highlight() {
                uploadArea.classList.add('highlight');
            }
            
            function unhighlight() {
                uploadArea.classList.remove('highlight');
            }
            
            // 处理文件拖放
            uploadArea.addEventListener('drop', handleDrop, false);
            
            function handleDrop(e) {
                const dt = e.dataTransfer;
                const files = dt.files;
                if (files.length > 0) {
                    handleFiles(files);
                }
            }
            
            // 处理文件选择
            fileInput.addEventListener('change', function() {
                if (fileInput.files.length > 0) {
                    handleFiles(fileInput.files);
                }
            });
            
            function handleFiles(files) {
                selectedFile = files[0];
                if (!selectedFile.type.match('image.*')) {
                    showError('请选择有效的图像文件');
                    return;
                }
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = new Image();
                    img.onload = function() {
                        originalImageContainer.innerHTML = '';
                        originalImageContainer.appendChild(img);
                        originalImageInfo.innerHTML = `<p>尺寸: ${img.naturalWidth} x ${img.naturalHeight} 像素</p>`;
                        uploadBtn.disabled = false;
                        statusMessage.textContent = '已选择图像。点击"放大图像"按钮开始处理。';
                        hideError();
                    };
                    img.src = e.target.result;
                };
                reader.readAsDataURL(selectedFile);
            }
            
            // 处理上传按钮点击
            uploadBtn.addEventListener('click', function() {
                if (!selectedFile) {
                    showError('请先选择一张图片');
                    return;
                }
                
                uploadBtn.disabled = true;
                statusMessage.textContent = '处理图像中... 这可能需要一些时间。';
                loadingSpinner.style.display = 'block';
                upscaledImageContainer.innerHTML = '<p>处理中...</p>';
                upscaledImageInfo.innerHTML = '';
                downloadBtn.style.display = 'none';
                hideError();
                
                const formData = new FormData();
                formData.append('image', selectedFile);
                
                fetch('/upscale', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('服务器错误');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.error) {
                        throw new Error(data.error);
                    }
                    
                    const img = new Image();
                    img.onload = function() {
                        upscaledImageContainer.innerHTML = '';
                        upscaledImageContainer.appendChild(img);
                        upscaledImageInfo.innerHTML = `<p>尺寸: ${img.naturalWidth} x ${img.naturalHeight} 像素</p>`;
                        
                        // 使用下载URL而不是data URL
                        if (data.download_url) {
                            console.log("设置下载URL:", data.download_url);
                            // 重新创建下载按钮以避免可能的缓存问题
                            const newDownloadBtn = document.createElement('a');
                            newDownloadBtn.href = data.download_url;
                            newDownloadBtn.className = 'download-btn';
                            newDownloadBtn.textContent = '下载放大后的图像';
                            newDownloadBtn.setAttribute('target', '_blank');
                            newDownloadBtn.setAttribute('download', '');
                            
                            // 替换原下载按钮
                            const oldBtn = document.getElementById('download-btn');
                            oldBtn.parentNode.replaceChild(newDownloadBtn, oldBtn);
                            newDownloadBtn.id = 'download-btn';
                            newDownloadBtn.style.display = 'block';
                        } else {
                            // 后备方案，使用data URL
                            downloadBtn.href = data.upscaled_image;
                            downloadBtn.download = '放大_' + selectedFile.name;
                            downloadBtn.style.display = 'block';
                        }
                    };
                    img.src = data.upscaled_image;
                    
                    statusMessage.textContent = '图像成功放大！';
                    uploadBtn.disabled = false;
                })
                .catch(error => {
                    showError('错误: ' + error.message);
                    upscaledImageContainer.innerHTML = '<p>处理失败</p>';
                    uploadBtn.disabled = false;
                })
                .finally(() => {
                    loadingSpinner.style.display = 'none';
                });
            });
            
            function showError(message) {
                errorMessage.textContent = message;
                errorMessage.style.display = 'block';
            }
            
            function hideError() {
                errorMessage.textContent = '';
                errorMessage.style.display = 'none';
            }
        });
    </script>
</body>
</html>
